package GroupChats;

import java.io.*;
import java.net.Socket;

public class MyThread1 extends Thread{

    private final Socket socket;
    public MyThread1(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            while (true) {
                try {
                    String s = dataInputStream.readUTF();
                    System.out.println(s);

                    //发送到群聊中
                    sendAll(s);

                } catch (Exception e) {
                    System.out.println(socket.getRemoteSocketAddress() + "已下线了!!!");
                    Server.socketList.remove(socket);
                    dataInputStream.close();
                    inputStream.close();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendAll(String msg) throws IOException {
        for (Socket soc : Server.socketList) {
            OutputStream os = soc.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(msg);
            dos.flush();
        }

    }
}
